<template>
  <div class="log-box">
    <!-- <p class="tip">Click on button in image container</p>  #626aef -->
    <div class="cont">
      <div class="form sign-in">
        <el-button
          v-if="islang"
          plain
          color="#BE7AEB"
          style="width:30%;margin-top:-8%;margin-right:-2%;"
          @click="changeLang('zh')"
        >
          <p style="font-weight:700;color:#473652">
            Switch to Chinese
            <el-icon><InfoFilled /></el-icon>
          </p>
        </el-button>
        <el-button v-if="!islang" plain color="#BE7AEB" style="width:20%;margin-top:-8%;margin-right:-2%;" @click="changeLang('en')">
          <p style="font-weight:700;color:#473652">
            切换为英文
          </p>
        </el-button>
        
        <h2>{{$t('loginForm.describe')}}</h2>
        <label>
          <span>{{$t('loginForm.accountTitle')}}</span>
          <input
            v-model="loginFormDto.loginAccount"
            type="text"
            :placeholder="$t('loginForm.account')"
          />
        </label>
        <label>
          <form>
            <span>{{$t('loginForm.pwdTitle')}}</span>
            <input
              v-model="loginFormDto.loginPwd"
              type="password"
              :placeholder="$t('loginForm.password')"
              show-password="true"
              autocomplete="off"
            />
          </form>
        </label>
        <label>
          <input
            style="width:20%;display:inline-block"
            v-model="loginFormDto.loginValidityDay"
            type="radio"
            name="loginValidity"
            value="1"
            checked
          />
          <p style="display:inline-block;color:gray; font-family: monospace;">一小时有效</p>
          <input
            style="width:20%;display:inline-block"
            v-model="loginFormDto.loginValidityDay"
            type="radio"
            name="loginValidity"
            value="24"
          />
          <p style="display:inline-block;color:gray; font-family: monospace;">今天有效</p>
        </label>
        <p class="forgot-pass">{{$t('loginForm.forgetPwd')}}</p>
        <el-button class="submit" :loading = "btnLoading" @click="clickLoginFun">{{$t('loginForm.loginBtn')}}</el-button>
        <el-button class="fb-btn" @click="backPlanetIndex">
            {{$t('loginForm.gotoIndex')}} <span>{{$t('loginForm.indexPage')}}</span>
        </el-button>
      </div>
      <div class="sub-cont">
        <div class="img">
          <div class="img__text m--up">
            <h2>{{$t('loginForm.leftDescribeTitle')}}</h2>
            <p>{{$t('loginForm.leftDescribe')}}</p>
          </div>
          <div class="img__text m--in">
            <h2>{{$t('loginForm.rightDescribeTitle')}}</h2>
            <p>{{$t('loginForm.rightDescribe')}}</p>
          </div>
          <div class="img__btn">
            <span class="m--up">{{$t('loginForm.clickRegister')}}</span>
            <span class="m--in">{{$t('loginForm.clickLoginIn')}}</span>
          </div>
        </div>
        <div class="form sign-up">
          <!-- 语言切换按钮 -->
          <el-button v-if="islang"  plain color="#BE7AEB" style="width:30%;margin-top:-8%;margin-right:-4%;" @click="changeLang('zh')">
            <p style="font-weight:700;color:#473652">Switch to Chinese</p>
          </el-button>
          <el-button v-if="!islang" plain  color="#BE7AEB" style="width:30%;margin-top:-8%;margin-right:-4%;" @click="changeLang('en')">
              <p style="font-weight:700;color:#473652">切换为英文</p>
          </el-button>
          <h2> {{$t('loginForm.regDescribe')}} </h2>
          <label>
              <span>{{$t('loginForm.accountTitle')}}</span>
              <input type="text" v-model="loginFormDto.loginAccount" :placeholder="$t('loginForm.account')"/> 
          </label>
          <label>
              <form>
                  <span>{{$t('loginForm.pwdTitle')}}</span>
                  <input type="password" v-model="loginFormDto.loginPwd" :placeholder="$t('loginForm.password')" autocomplete="off" />
              </form>
          </label>
          <label>
              <span>{{$t('loginForm.imgcode')}}</span>
              <input type="text" v-model="loginFormDto.imgCode" :placeholder="$t('loginForm.imgcode')"/>
          </label>
          <button type="button" class="submit" @click="registerAccount" :loading = "btnLoading">{{$t('loginForm.clickRegister')}}</button>
          <button type="button" class="fb-btn" @click="backPlanetIndex">
            {{$t('loginForm.regGotoIndex')}} <span>{{$t('loginForm.indexPage')}}</span>
          </button>
          <div class="reg-tip">
              <el-link type="success" @click="regNotice($t('loginForm.btnTip'))">{{$t('loginForm.regNotice')}}</el-link> 
          </div>
        </div>
      </div>
    </div>

    <a href="#" @click="backPlanetIndex" target="_blank" class="icon-link">
        <img src="http://icons.iconarchive.com/icons/uiconstock/socialmedia/256/Dribbble-icon.png">
    </a>
    <a href="#" @click="backPlanetIndex" target="_blank" class="icon-link icon-link--twitter">
        <img src="https://cdn1.iconfinder.com/data/icons/logotypes/32/twitter-128.png">
    </a>
  </div>
</template>

<script>
import { ref, getCurrentInstance, reactive } from 'vue'
import { onMounted } from 'vue-demi'
import router from '@/router'
import { useI18n } from 'vue-i18n'
import { useDark } from '@vueuse/core'
import {debounce, gatewayPrefix, userMiddleContextPath,currentUser,token,authorization} from '@/utils/commConstance'
import { ElMessage,ElMessageBox,ElNotification  } from 'element-plus'
import { $http } from '@/utils/axios.js'
import { InfoFilled } from '@element-plus/icons-vue';
import { useStore } from 'vuex' 
export default {
  components:{
      InfoFilled
  },
  setup() {
    let store = useStore()
    onMounted(() => {
      document
        .querySelector('.img__btn')
        .addEventListener('click', function () {
          debounceFun()
        })
    })

    let allData = reactive({
      loginFormDto: {
        loginAccount: '',
        loginPwd: '',
        loginValidityDay: 1,
        imgCode: ''
      },
    })
    const isDark = ref(useDark())
    const btnLoading = ref(false)
    let islang = ref(false)
    const { locale } = useI18n()
    //防抖
    const debounceFun = debounce(() => {
      document.querySelector('.cont').classList.toggle('s--signup')
    }, 200)
    //国际化配置
    function changeLang(lang) {
      if (lang === 'zh') {
        islang.value = false
      } else {
        islang.value = true
      }
      locale.value = lang
      // 重要！下面遇到问题里解释
      localStorage.setItem('lang', lang)
    }
    const backPlanetIndex = () => {
      router.push('/')
    }
    // 登录
    const loginCheck = () => {
        
        if (
            allData.loginFormDto.loginAccount == null ||
            allData.loginFormDto.loginAccount == ''
        ) {
            return ElMessage.warning('用户名和密码不能为空!!!')
        }
        if (
            allData.loginFormDto.loginPwd == null ||
            allData.loginFormDto.loginPwd == ''
        ) {
            return ElMessage.warning('用户名和密码不能为空!!!')
        }
        btnLoading.value = true
        $http.post(`${gatewayPrefix}/${userMiddleContextPath}/userOperation/planetLogin`,allData.loginFormDto).then((res) => {
            if(res.isLoginSuccess){
                sessionStorage.setItem(token,res.loginUserInfo.token)
                sessionStorage.setItem(currentUser,JSON.stringify(res.loginUserInfo))
                sessionStorage.setItem(authorization,res.sign)
                //弃用
                store.commit('setUserSignAuthInfo',res.sign)
                allData.loginFormDto.loginAccount = ''
                allData.loginFormDto.loginPwd = ''
                router.push('/')                            
            }
        }).finally(()=>{
          btnLoading.value = false
        })
    }
    const clickLoginFun = debounce(loginCheck, 300)

    // 注册
    const registerCheck = ()=>{
        btnLoading.value = true
        if ( allData.loginFormDto.loginAccount == null ||allData.loginFormDto.loginAccount == '' ) {
            btnLoading.value = false
            return ElMessage.warning('用户名和密码不能为空!!!')
        }
        if ( allData.loginFormDto.loginPwd == null || allData.loginFormDto.loginPwd == '') {
            btnLoading.value = false
            return ElMessage.warning('用户名和密码不能为空!!!')
        }
        let accountReg = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/
        let pwdReg = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,10}$/
        if(!accountReg.test(allData.loginFormDto.loginAccount)){
            btnLoading.value = false
            return ElMessage.warning('账号校验失败,(字母开头，允许5-16字节，允许字母数字下划线)')
        }
        if(!pwdReg.test(allData.loginFormDto.loginPwd)){
            btnLoading.value = false
            return ElMessage.warning('密码校验失败,(必须包含大小写字母和数字的组合，可以使用特殊字符，长度在6-10之间)')
        }
        $http.post(`${gatewayPrefix}/${userMiddleContextPath}/userOperation/planetRegister`,allData.loginFormDto).then((res) => {
            if(!res){
                return ElMessage.error('用户注册失败，请联系管理员')
            }
            ElMessage.success("注册成功,快登录吧")
            btnLoading.value = false
            allData.loginFormDto.loginAccount = ''
            allData.loginFormDto.loginPwd = ''  
        }).catch((err) =>{
            console.log('planet register error:', err)
            btnLoading.value = false
            ElMessage.error("注册失败,请联系管理员===>"+ err.response)
        })
    }
    const registerAccount = debounce(registerCheck, 300)

    const regNotice = (tip)=>{
        ElNotification({
            title: 'tip',
            message: tip,
            type: 'success',
        })
    }

    return {
      changeLang,
      backPlanetIndex,
      isDark,
      islang,
      clickLoginFun,
      ...allData,
      btnLoading,
      registerAccount,
      regNotice
    }
  }
}
</script>

<style src = "../assets/css/planetLogin.css" scoped></style>